package com.tiger.converter;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

import org.apache.commons.lang3.StringUtils;

@Converter
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, String> {
	
	private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
	
	@Override
	public String convertToDatabaseColumn(LocalDateTime entityValue) {
		return entityValue == null ? null : formatter.format(entityValue);
	}
	
	@Override
	public LocalDateTime convertToEntityAttribute(String databaseValue) {
		return StringUtils.isEmpty(databaseValue) ? null : LocalDateTime.parse(databaseValue.length() == 19 ? databaseValue : databaseValue.substring(0, 19), formatter);
	}

}
